var models = require('../mysql/mysql');
var getDate = require('../utils/date')
var Token = require('../utils/jwtutil')
var multiparty = require('multiparty')
/**
 * 获取所有商品信息
 * url: /goods/list
 * method: get
 *  */ 
const getAllList = async (req, res, next) => {
    // 接收参数
    var sql = `select * from goods`;
    let data = await models(sql)

    if (data.length > 0) {
        res.send({
            code: 1,
            info:data
        })
    } else {
        res.send({
            code: -1,
            info: '商品列表为空!',
        })
    }
}
/**
 * 商品列表接口
 * url: /goods/list
 * method: get
 */
const getGoodsList = async (req, res, next) => {
	// 接收参数
	const {
		pageSize = 10, pageNum = 1, name, shop, startPrice, endPrice
	} = req.query
	// console.log(req.query);
	// let wherestr = `where product="${name}" and shop="${shop}"`
	let namestr = `product="${name}"`
	let shopstr = `shop="${shop}"`
	let startPricestr = `price>=${startPrice}`
	let endPricestr = `price<=${endPrice}`
	let allPricestr = `${startPrice}<price<${endPrice}`
	let wherestr = ``
	if (name || shop || startPrice || endPrice) {
		wherestr += `where`
		wherestr += ` ${name?namestr:''}`
		// console.log(wherestr);
		if (name && (shop || startPrice || endPrice)) {
			wherestr += ` and`
		}
		wherestr += ` ${shop?shopstr:''}`
		// console.log(wherestr);
		if (shop && (startPrice || endPrice)) {
			wherestr += ` and`
		}

		// if(startPrice && endPrice) wherestr += ` ${allPricestr}`
		// else if (startPrice) wherestr += ` ${startPrice?startPricestr:''}`
		// else if (endPrice) wherestr += ` ${endPrice?endPricestr:''}`

		wherestr += ` ${startPrice?startPricestr:''}`
		// console.log(wherestr);
		if (startPrice && endPrice) {
			wherestr += ` and`
		}
		wherestr += ` ${endPrice?endPricestr:''}`
		console.log(wherestr);
	}
	// let wherestr = `where price>${Number(startPrice)}`
	let count = await models(`select count(*) from goods ${wherestr}`)
	// let count = await models(`select count(*) from goods where price>=3000 and price<=5000`)
	// console.log(count[0]['count(*)']);
	let offset = (Number(pageNum) - 1) * Number(pageSize)
	var sql = `select * from goods ${wherestr} limit ${pageSize} offset ${offset}`;
	// var sql = `select * from goods where price>=3000 and price<=5000 limit ${pageSize} offset ${offset}`; 
	let data = await models(sql)
	// console.log(data.length);

	if (data.length > 0) {
		res.send({
			code: 1,
			info: {
				total: count[0]['count(*)'],
				list: data,
			},
		})
	} else {
		res.send({
			code: -1,
			info: '商品列表为空!',
		})
	}
}
/**
 * 订单列表接口
 * url: /goods/orderlist
 * method: get
 */
const getOrderList = async (req, res, next) => {
	// console.log('req.headers.authorization>>>',req.headers.authorization); // undefined 疑似要设置cookie
	// 接收参数
	const {
		pageSize = 10, pageNum = 1, name, shop, startPrice, endPrice
	} = req.query
	let namestr = `number='${name}'`
	let shopstr = `user='${shop}'`
	let startPricestr = `total_price>='${startPrice}'`
	let endPricestr = `total_price<='${endPrice}'`
	// let allPricestr = `${startPrice}<price<${endPrice}`
	let wherestr = ``
	if (name || shop || startPrice || endPrice) {
		wherestr += `where`
		wherestr += ` ${name?namestr:''}`
		// console.log(wherestr);
		if (name && (shop || startPrice || endPrice)) {
			wherestr += ` and`
		}
		wherestr += ` ${shop?shopstr:''}`
		// console.log(wherestr);
		if (shop && (startPrice || endPrice)) {
			wherestr += ` and`
		}
		wherestr += ` ${startPrice?startPricestr:''}`
		// console.log(wherestr);
		if (startPrice && endPrice) {
			wherestr += ` and`
		}
		wherestr += ` ${endPrice?endPricestr:''}`
		console.log(wherestr);
	}
	// let count = await models(`select count(*) from orders_list where user="admin"`)
	let count = await models(`select count(*) from orders ${wherestr}`)
	let offset = (Number(pageNum) - 1) * Number(pageSize)
	// var sql = `select * from orders_list where user="admin" limit ${pageSize} offset ${offset}`; 
	var sql = `select * from orders ${wherestr} limit ${pageSize} offset ${offset}`;
	let data = await models(sql)

	if (data.length > 0) {
		res.send({
			code: 1,
			info: {
				total: count[0]['count(*)'],
				list: data,
			},
		})
	} else {
		res.send({
			code: -1,
			info: '商品列表为空!',
		})
	}
}
// /**
//  * 订单详情
//  * 根据订单id查找订单
//  *  get
//  *   url: /goods/detail?id=1
//  *        /goods/1
//  */
const getOrderById = async (req, res, next) => {
	// 接收参数
	const {
		id
	} = req.query
	var sql = `select * from orders where id=${id}`;
	let data = await models(sql)

	if (data.length > 0) {
		res.send({
			code: 1,
			info: {
				list: data,
			},
		})
	} else {
		res.send({
			code: -1,
			info: '该订单不存在!',
		})
	}
}
// /**
//  * 所有订单
//  *  get
//  *   url: /goods/detail?id=1
//  *        /goods/1
//  */
const getAllOrderById = async (req, res, next) => {
	// 接收参数
	var sql = `select * from orders`;
	let data = await models(sql)

	if (data.length > 0) {
		res.send({
			code: 1,
			info: {
				list: data,
			},
		})
	} else {
		res.send({
			code: -1,
			info: '订单列表为空!',
		})
	}
}
// /**
//  * 确认发货/提货订单
//  *  post
//  *   url: /goods/confirmorder
//  *        /goods/1
//  */
const getConfirmOrder = async (req, res, next) => {
	// 接收参数
	console.log(req.body)
	const {order_state,id} = req.body
	var sql = `update orders set order_state="${order_state}" where id='${id}';`

	try {
		await models(sql)
		res.send({
			code: 1,
			info: '修改成功',
		})
	} catch (eror) {
		res.send({
			code: -1,
			info: '修改失败',
		})
	}
}
// /**
//  * 商品详情
//  * 根据商品id查找商品
//  *  get
//  *   url: /goods/detail?id=1
//  *        /goods/1
//  */
const getGoodsById = async (req, res, next) => {
	// 接收参数
	console.log(req.query);
	const {
		id
	} = req.query
	var sql = `select * from goods where id=${id}`;
	let data = await models(sql)

	if (data.length > 0) {
		res.send({
			code: 1,
			info: {
				list: data,
			},
		})
	} else {
		res.send({
			code: -1,
			info: '商品列表为空!',
		})
	}
}
// /**
//  * 商品分类列表
//  * 根据商品分类id查找对于列表
//  *  get
//  *   url: /goods/detail?id=1
//  *        /goods/1
//  */
const getGoodsByClassifyid = async (req, res, next) => {
	// 接收参数
	console.log(req.query);
	const {
		categoryId
	} = req.query
	var sql = `select * from goods where category_id=${categoryId}`;
	let data = await models(sql)

	if (data.length > 0) {
		res.send({
			code: 1,
			info: {
				list: data,
			},
		})
	} else {
		res.send({
			code: -1,
			info: '商品列表为空!',
		})
	}
}
/**
 * 添加商品接口
 * url: /goods/add
 * method: post
 * 参数:  pid pname  price  putaway category_id
 */
const addGoods = async (req, res, next) => {
	const imgurl = '' + req.file.filename
	const {
		categoryId,
		product,
		shop,
		price,
		oldprice,
		putaway
	} = req.body
	console.log(imgurl);
	console.log(req.body);
	var sql = `insert into goods(product,shop,price,oldprice,putaway,category_id,img_url,sales_volume) 
	values("${product}","${shop}",${price},${oldprice},${putaway},${categoryId},'${imgurl}','0')`;

	try {
		await models(sql)
		res.send({
			code: 1,
			info: '添加成功',
		})
	} catch (eror) {
		res.send({
			code: -1,
			info: '添加失败',
		})
	}
}
/**
 * 编辑商品接口
 * url: /goods/edit
 * method: post
 * 参数:  pid pname  price  putaway category_id
 */
const editGoods = async (req, res, next) => {
	const imgurl = '' + req.file.filename
	const {
		categoryId,
		product,
		shop,
		price,
		oldprice,
		putaway,
		id
	} = req.body
	console.log(req.body);
	// var sql = `insert into goods(product,shop,price,oldprice,putaway,category_id,img_url) 
	// values("${product}","${shop}",${price},${oldprice},${putaway},${categoryId},'${imgurl}')`; 
	var sql = `update goods set product="${product}",shop="${shop}",price=${price},oldprice=${oldprice},putaway=${putaway},
	category_id=${categoryId},img_url="${imgurl}" where id=${id};`
	try {
		await models(sql)
		res.send({
			code: 1,
			info: '修改成功',
		})
	} catch (eror) {
		res.send({
			code: -1,
			info: '修改失败',
		})
	}
}
/**
 * 修改订单接口
 * url: /goods/edit
 * method: post
 * 参数:  pid pname  price  putaway category_id
 */
const editOrder = async (req, res, next) => {
	console.log(req.body)
	const {
		id,
		orderState
	} = req.body
	var sql = `update orders set order_state=${orderState} where id=${id};`
	try {
		await models(sql)
		res.send({
			code: 1,
			info: '修改成功',
		})
	} catch (eror) {
		res.send({
			code: -1,
			info: '修改失败',
		})
	}
}
/**
 * 修改商品销量接口
 * url: /goods/edit_sales_volume
 * method: post
 * 参数:  ids , numbers
 */
const addSalesVolume = async (req, res, next) => {
	// console.log(req.body)
	const { updataArr } = req.body
	console.log('updataArr>>>',updataArr);
	// updataArr = [
	// 	{id:1,number:'100'},
	// 	{id:2,number:'200'},
	// 	{id:3,number:'50'},
	// ]

	// var sql = `update goods set sales_volume=sales_volume+'1' where id=1;`
	// var sql = `replace into goods(id, sales_volume) values (1,'200'),(2,'300'),(3,'400');`
	try {
		updataArr.forEach(async (item)=>{
			var sql = `update goods set sales_volume=sales_volume+'${item.number}' where id=${item.id};`
			await models(sql)
		})
		res.send({
			code: 1,
			info: '修改成功',
		})
	} catch (eror) {
		res.send({
			code: -1,
			info: '修改失败',
		})
	}
}
/**
 * 提交订单接口
 * url: /goods/order
 * method: post
 * 参数:  id user total_price
 */
const addOrder = async (req, res, next) => {
	// 接收参数
	console.log(req.body);
	let number = getDate().split(' ')[0].split('-').join('') + Math.floor(Math.random() * 200000 + 100000)
	// getNowDate().split(' ')[0].split('-').join('')
	const {
		user,
		totalPrice,
		userAdInfo,
		goodsInfo
	} = req.body
	// console.log(JSON.stringify(userAdInfo));
	// console.log(goodsInfo);
	// console.log(JSON.stringify(goodsInfo));
	var sql = `insert into orders(number,date,user,total_price,pay_state,order_from,order_state,user_ad_info,goods_info,date_s) 
	values(${number},"${getDate()}","${user}",${totalPrice},"1","APP","1",'${JSON.stringify(userAdInfo)}','${JSON.stringify(goodsInfo)}','${req._startTime}')`;

	try {
		await models(sql)
		res.send({
			code: 1,
			info: '添加成功',
		})
	} catch (eror) {
		res.send({
			code: -1,
			info: '添加失败',
		})
	}
}
// /**
//  * 删除订单
//  * /goods/deleteorder
//  * /goods/1
//  * delete
//  *  post请求参数 req.body
//  *
//  */
const delteOrdersById = async (req, res, next) => {
	// 接收参数
	console.log(req.body);
	const {
		id
	} = req.body
	var sql = `delete from orders where id="${id}"`;

	try {
		await models(sql)
		res.send({
			code: 1,
			info: '删除成功',
		})
	} catch (eror) {
		res.send({
			code: -1,
			info: '删除失败',
		})
	}
}
// /**
//  * 删除商品
//  * /goods/delete?id=1
//  * /goods/1
//  * delete
//  *  get请求参数 req.query
//  *  post请求参数 req.body
//  *
//  */
const delteGoodsById = async (req, res, next) => {
	// // token认证
	let token = req.headers.authorization
	console.log('token>>>', token);
	// if (!token) {
	// 	res.send({
	// 		code: -1,
	// 		info: 'token不存在!'
	// 	})
	// 	return
	// }
	// let tokenObj = Token.decrypt(token)
	// if (!tokenObj.token) {
	// 	res.send({
	// 		code: -1,
	// 		info: 'token验证失败!'
	// 	})
	// 	return
	// }
	// next()
	// 接收参数
	console.log(req.body);
	const {
		id
	} = req.body
	var sql = `delete from goods where id="${id}"`;

	try {
		await models(sql)
		res.send({
			code: 1,
			info: '删除成功',
		})
	} catch (eror) {
		res.send({
			code: -1,
			info: '删除失败',
		})
	}
}
// /**
//  * 批量删除商品
//  * /goods/delete?id=1
//  * /goods/1
//  * delete
//  *  get请求参数 req.query
//  *  post请求参数 req.body
//  *
//  */
const batchDeleteGoodsById = async (req, res, next) => {
	// 接收参数
	console.log(req.body);
	const {
		id
	} = req.body

	var sql = `delete from goods where id in(31,32)"`;

	try {
		await models(sql)
		res.send({
			code: 1,
			info: '批量删除成功',
		})
	} catch (eror) {
		res.send({
			code: -1,
			info: '批量删除失败',
		})
	}
}


module.exports = {
	getGoodsList,
	getAllList,
	addGoods,
	delteGoodsById,
	getGoodsById,
	addOrder,
	editGoods,
	batchDeleteGoodsById,
	getGoodsByClassifyid,
	getOrderList,
	getOrderById,
	editOrder,
	delteOrdersById,
	getAllOrderById,
	getConfirmOrder,
	addSalesVolume
}